package io.kiki.stack.http.feign.form.spring;

import feign.codec.EncodeException;
import feign.form.multipart.AbstractWriter;
import feign.form.multipart.Output;
import lombok.experimental.FieldDefaults;
import lombok.val;
import org.springframework.web.multipart.MultipartFile;

import static lombok.AccessLevel.PRIVATE;

/**
 * A Spring multiple files writer.
 *
 * @author Artem Labazin
 */
@FieldDefaults(level = PRIVATE, makeFinal = true)
public class SpringManyMultipartFilesWriter extends AbstractWriter {

    SpringSingleMultipartFileWriter fileWriter = new SpringSingleMultipartFileWriter();

    @Override
    public boolean isApplicable(Object value) {
        if (value instanceof MultipartFile[]) {
            return true;
        }
        if (!(value instanceof Iterable)) {
            return false;
        }
        val iterable = (Iterable<?>) value;
        val iterator = iterable.iterator();
        return iterator.hasNext() && iterator.next() instanceof MultipartFile;
    }

    @Override
    public void write(Output output, String boundary, String key, Object value) throws EncodeException {
        if (value instanceof MultipartFile[]) {
            val files = (MultipartFile[]) value;
            for (val file : files) {
                fileWriter.write(output, boundary, key, file);
            }
        } else
            if (value instanceof Iterable) {
                val iterable = (Iterable<?>) value;
                for (val file : iterable) {
                    fileWriter.write(output, boundary, key, file);
                }
            } else {
                throw new IllegalArgumentException();
            }
    }
}
